package com.yf.controller.api.course;

import com.yf.annotation.IgnoreAuth;
import com.yf.annotation.LoginUser;
import com.yf.entity.UserEntity;
import com.yf.response.R;
import com.yf.service.WxPayService;
import com.yf.service.course.LessonOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
@RequestMapping("/api/course")
public class ApiCourseOrderController {

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private LessonOrderService lessonOrderService;



    /**
     * 提交订单
     * @return
     * @Param handle: 购买类型   0，全章购买    1，单节购买
     * @Param id:  lessonId 或者 courseId
     */
    @GetMapping("/order/commit")
    public R commitOrder(@LoginUser UserEntity userEntity,Long id,Integer handle){
        return R.ok(lessonOrderService.order(userEntity.getId(),id, handle));
    }


    /**
     * 统一下单
     * @return
     * @Param   type:  0,购买课程    1，购买活动
     *
     */
    @PostMapping("/wx/to/pay")
    public R wxToPay(String orderNo, Double amount,String orderInfo,Integer type, HttpServletRequest request, @LoginUser UserEntity userEntity){
        String url = "";
        if(0==type){
            url = ServletUriComponentsBuilder.fromContextPath(request).path("/api/course/wx/pay").build().toString();
        }else {
            url = ServletUriComponentsBuilder.fromContextPath(request).path("/api/activity/wx/pay").build().toString();
        }
        String jsApiParam = wxPayService.createPayConfig(orderNo,amount,orderInfo,userEntity.getPayId(),url);
        return R.ok(jsApiParam);
    }


    /**
     * 支付成功回调地址
     * @return
     */
    @RequestMapping("/wx/pay")
    @IgnoreAuth
    public String wxPay(@RequestBody String body){
        Map<String,String> result = wxPayService.handleWxNotice(body);
        String orderNo = result.get("out_trade_no");
        String totalFee = result.get("total_fee"); //单位 分
        //TODO 如果orderNo的订单状态是没有支付的  改变订单的支付状态  验证支付金额是否正确 保存在学习课程记录
        lessonOrderService.updatePayStatus(orderNo,totalFee);
        //通知微信 已经收到通知
        return "<xml>\n" +
                "\n" +
                "  <return_code><![CDATA[SUCCESS]]></return_code>\n" +
                "  <return_msg><![CDATA[OK]]></return_msg>\n" +
                "</xml>";
    }

}
